<template>
  <view class="container">
    <view class="form">
      <u-form :model="form" :rules="rules" ref="uForm" labelWidth="100">
        <u-form-item label="房源" prop="houseId" borderBottom required>
          <u-input v-model="form.premisesAddress" placeholder="请选择"
                   disabled></u-input>
        </u-form-item>
        <u-form-item label="预约人" prop="contactsName" required>
          <u-input v-model="form.contactsName" placeholder="请输入报修人姓名" maxlength="10"></u-input>
        </u-form-item>
        <u-form-item label="手机号" prop="contactsPhone" required>
          <u-input v-model="form.contactsPhone" placeholder="请输入联系电话" maxlength="11"></u-input>
        </u-form-item>
        <!--    期望上门时间    -->
        <u-form-item label-width="200rpx" label="预约时间" prop="expectDate" required>
          <u-row :gutter="10">
            <u-col span="6">
              <uni-data-select v-model="form.expectDate"
                               :localdata="sevenDays"></uni-data-select>
            </u-col>
            <u-col span="6">
              <uni-data-select v-model="form.expectTime" :disabled="!form.expectDate"
                               :localdata="timeArr().map(item => ({text: item.value, value: item.value,disable:item.disabled}))"></uni-data-select>
            </u-col>
          </u-row>
        </u-form-item>
        <!--    期望入住时间    -->
        <u-form-item label="期望入住时间" prop="expectCheckInType" borderBottom required>
          <u-input v-model="form.expectCheckInTypeLabel" placeholder="请选择" @tap="expectCheckInTypeShow = true"
                   readonly suffix-icon="arrow-down"></u-input>
        </u-form-item>
        <!--    指定带看员    -->
        <u-form-item label="指定带看员" prop="expectBusUserId" borderBottom required>
          <u-input v-model="form.expectBusUserLabel" placeholder="请选择" @tap="expectBusUserShow = true"
                   readonly suffix-icon="arrow-down"></u-input>
        </u-form-item>
        <u-form-item label="备注" prop="workOrderRemark">
          <u-textarea v-model="form.workOrderRemark" placeholder="请输入备注信息" maxlength="200" count></u-textarea>
        </u-form-item>
      </u-form>
      <!--    期望入住时间选择器   -->
      <u-picker ref="expectCheckInTypePicker" :show="expectCheckInTypeShow" :columns="[dict.type.expect_check_in_type]"
                keyName="label"
                @confirm="confirmExpectCheckIn"
                :immediate-change="true"
                @cancel="expectCheckInTypeShow = false"></u-picker>
      <!--    指定带看员选择器   -->
      <u-picker ref="expectBusUserPicker" :show="expectBusUserShow" :columns="[workerList]" keyName="label"
                @confirm="confirmExpectBusUser"
                :immediate-change="true"
                @cancel="expectBusUserShow = false"></u-picker>
    </view>
    <view class="container-footer">
      <view class="btn">
        <u-button type="default" @click="beforeCancel" plain>取消</u-button>
      </view>
      <view class="btn">
        <u-button type="primary" @click="handleSubmit">{{ workOrderId ? '提交修改' : '立即预约' }}</u-button>
      </view>
    </view>
  </view>
</template>
<script>
import {compareDateTime, DateCompare, getDateName, getDateRange} from "@/utils/time";
import {houseList} from "@/api/manager/order";
import {
  getWorkOrderDetail,
  addWorkOrder,
  editWorkOrder,
  deleteWorkOrder, getMaintenanceWorkerInfo
} from "@/api/manager/workOrder";

import storage from "@/utils/storage";
import constant from "@/utils/constant";

export default {
  name: 'add',
  dicts: ['expect_check_in_type'],
  data() {
    return {
      house: {}, // 房屋信息
      // 工单id
      workOrderId: null,
      // 指定带看员
      expectBusUserShow: false,
      // 期望入住选择器
      expectCheckInTypeShow: false,
      // 期望上门日期选择器
      expectDateShow: false,
      // 期望上门时间选择器
      expectTimeShow: false,
      // 维修房源列表
      houseList: [],
      // 工单人员列表
      workerList: [],
      // 表单数据
      form: {
        houseId: '',
        premisesAddress: '',
        contactsName: '',
        contactsPhone: '',
        expectDate: '',
        expectTime: '',
        urgencyDegree: '1',
        workOrderRemark: '',
        faultPictureList: [],
        expectCheckInType: '',
        expectCheckInTypeLabel: ''
      },
      rules: {
        houseId: [
          {required: true, message: '请选择维修房源', trigger: ['change', 'blur']}
        ],
        contactsName: [
          {required: true, message: '请输入报修人姓名', trigger: ['change', 'blur']},
        ],
        contactsPhone: [
          {required: true, message: '请输入联系电话', trigger: ['change', 'blur']},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['change', 'blur']}
        ],
        expectDate: [
          {required: true, message: '请选择期望上门日期', trigger: ['change', 'blur']},
          {
            validator: (rule, value, callback) => {
              if (!this.form.expectTime) {
                callback(new Error('请选择期望上门时间'))
              }
              callback()
            },
            trigger: ['change', 'blur']
          }
        ],
        expectCheckInType: [
          {required: true, message: '请选择期望入住时间', trigger: ['change', 'blur']}
        ],
        expectBusUserId: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请选择指定带看员'))
              }
              callback()
            },
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  computed: {
    // 获取今天以及七天日期的对象数组
    sevenDays() {
      const today = new Date()    // 获取今天的日期对象
      // 获取七天后的日期对象
      const sevenDaysAfter = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
      const dateArr = getDateRange(today, sevenDaysAfter);
      let result = []
      for (let i = 0; i < dateArr.length; i++) {
        result.push({
          label: getDateName(dateArr[i]),
          text: getDateName(dateArr[i]),
          value: dateArr[i]
        })
      }
      return result
    },
    // 获取时间段数组
    timeArr:{
      get(){
        return ()=>{
          const arr = []
          for (let i = 6; i < 24; i++) {
            let time = i < 10 ? '0' + i + ':00' : i + ':00'
            let dateTime = this.form.expectDate + ' ' + time+':00'
            let item = {
              disabled: compareDateTime(new Date(), dateTime,'>'),
              value: time
            }
            arr.push(item)
          }
          return arr
        }
      }
    },
    // 获取房间信息
    userInfo() {
      return storage.get(constant.userInfo)
    },
    // 获取时间列表
    timeList() {
      let list = []
      for (let i = 6; i <= 24; i++) {
        let item = i < 10 ? '0' + i + ':00' : i + ':00'
        let obj = {
          label: item,
          value: item
        }
        list.push(obj)
      }
      return list
    },
  },
  onLoad(options) {
    this.workOrderId = options.workOrderId || null;
    if (options.house) {
      this.house = JSON.parse(options.house)
    }
    // 设置页面标题
    let title = this.workOrderId ? '修改申请' : '预约看房';
    uni.setNavigationBarTitle({
      title: title
    });
    this.init()

  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    // 初始化页面数据
    init() {
      this.getHouseList()
      this.getMaintenanceWorkerInfo()
      this.form = {
        workOrderId: "",// 工单id
        workOrderType: '3', // 1.维修工单 2.保洁工单 3.看房工单
        expectCheckInType: '',
        expectCheckInTypeLabel: '',
        houseId: this.house.houseId,//房屋id
        premisesAddress: this.house.premisesAddress,//房屋地址
        contactsName: this.userInfo.userName,//报修人姓名
        contactsPhone: this.userInfo.userMobile,//报修人手机号
        expectDate: this.sevenDays[0].value,
        expectDateLabel: this.sevenDays[0].label,
        expectTime: '',
        expectTimeLabel: '',
        expectationStartTime: "", //期望上门开始时间
        expectationEndTime: "", //期望上门结束时间
        urgencyDegree: '1', //紧急程度(1.普通,2.紧急,3.非常紧急)
        workOrderRemark: '',//备注信息
        faultPictureList: [], //故障照片集合
        workOrderChargeItemList: [], //维修费用明细
        appointmentTime: '', //预约时间
        workOrderSource: "3", //工单来源(1.平台,2.B端小程序,3.C端小程序)
        expectBusUserId: '0', //指定带看员
        expectPersonName: '', //指定带看员姓名
        expectPersonTenantId: '', //指定带看员所属租户id
        expectBusUserLabel: '', //指定带看员姓名
      }
      if (this.workOrderId) {
        this.$nextTick(() => {
          getWorkOrderDetail(this.workOrderId).then(res => {
            if (res.code === 200) {
              this.form = res.data
              //期望日期数据
              this.form.expectDate = this.form.appointmentTime.split(' ')[0]
              this.form.expectTime = this.form.appointmentTime.split(' ')[1]
              this.form.expectBusUserId = this.form.expectBusUserId ? this.form.expectBusUserId : '0'

              // 期望入住
              this.setPickerData('expectCheckInTypePicker', this.form.expectCheckInType, this.dict.type.expect_check_in_type, 'expectCheckInType', 'expectCheckInTypeLabel')
              // 指定带看员
              this.setPickerData('expectBusUserPicker', this.form.expectBusUserId, this.workerList, 'expectBusUserId', 'expectBusUserLabel')
            }
          })
        })

      }
    },
    // 获取房源列表
    getHouseList() {
      houseList().then(res => {
        if (res.code === 200) {
          this.houseList = res.data.map(item => {
            return {
              label: item.premisesAddress,
              value: item.houseId
            }
          })
        }
      })
    },
    // 选择期望入住
    confirmExpectCheckIn(e) {
      this.form.expectCheckInType = e.value[0].value
      this.form.expectCheckInTypeLabel = e.value[0].label
      this.expectCheckInTypeShow = false
    },
    // 选择指定带看员
    confirmExpectBusUser(e) {
      console.log('e', e)
      this.form.expectBusUserId = e.value[0].value
      this.form.expectBusUserLabel = e.value[0].label
      this.form.expectPersonName = e.value[0].label
      this.form.expectPersonTenantId = e.value[0].tenantId
      this.expectBusUserShow = false
    },
    // 选定的值数据设置选择器默认值
    setPickerData(ref = '', value, list, valueKey, labelKey = '') {
      if (ref) {
        let index = list.findIndex(item => item.value === value)
        console.log('index', index, valueKey, list, value)
        if (index !== -1) {
          this.$refs[ref].setIndexs([index])
          this.form[valueKey] = list[index].value
          if (labelKey) {
            this.form[labelKey] = list[index].label
          } else {
            this.form[valueKey + 'Label'] = list[index].label
          }
        }

      }
    },
    //获取工单人员
    getMaintenanceWorkerInfo() {
      let params = {
        workOrderPersonName: '',
        workOrderPersonType: '3', // 1.维修工单 2.保洁工单 3.看房工单
        tenantId: '',
      }
      getMaintenanceWorkerInfo(params).then(res => {
        if (res.code === 200) {
          console.log('res', res)
          let random = {
            label: '随机分配',
            value: '0'
          };
          this.workerList = [random, ...res.data.map(item => {
            return {
              label: item.workOrderPersonName,
              value: item.busUserId,
              ...item
            }
          })]
        }
      })
    },
    // 取消前判断
    beforeCancel() {
      let text = this.workOrderId ? '确定要取消修改吗？' : '确定要取消申请吗？'
      uni.showModal({
        title: '提示',
        content: text,
        success: (res) => {
          if (res.confirm) {
            this.cancel()
          } else if (res.cancel) {
          }
        }
      })
    },
    // 取消
    cancel() {
      // 判断当前页面是否有上一页
      let pages = getCurrentPages()
      if (pages.length > 1) {
        // 页面栈中有上一页，则返回上一页
        this.$tab.navigateBack()
      } else {
        this.$tab.redirectTo('/pages/manager/workOrder/maintenance/list')
      }
    },
    // 提交
    handleSubmit() {
      this.$refs.uForm.validate().then(res => {
        console.log('res', res)
        if (res) {
          //期望上门时间处理
          this.form.appointmentTime = this.form.expectDate + ' ' + this.form.expectTime + ':00'
          console.log('form', this.form)
          let form = {
            workOrderId: this.form.workOrderId,
            workOrderType: this.form.workOrderType, // 1.维修工单 2.保洁工单 3.看房工单
            houseId: this.form.houseId, //房屋id
            premisesAddress: this.form.premisesAddress, //房屋地址
            contactsName: this.form.contactsName, //报修人姓名
            contactsPhone: this.form.contactsPhone, //报修人手机号
            expectDate: this.form.expectDate, //期望上门日期
            expectTime: this.form.expectTime, //期望上门时间
            expectationStartTime: this.form.expectationStartTime, //期望上门开始时间
            expectationEndTime: this.form.expectationEndTime, //期望上门结束时间
            urgencyDegree: this.form.urgencyDegree, //紧急程度(1.普通,2.紧急,3.非常紧急)
            workOrderRemark: this.form.workOrderRemark, //备注信息
            faultPictureList: this.form.faultPictureList, //故障照片集合
            workOrderChargeItemList: this.form.workOrderChargeItemList, //维修费用明细
            appointmentTime: this.form.appointmentTime, //预约时间
            workOrderSource: this.form.workOrderSource, //工单来源(1.平台,2.B端小程序,3.C端小程序)
            expectCheckInType: this.form.expectCheckInType, //期望入住类型
            expectBusUserId: this.form.expectBusUserId === '0' ? '' : this.form.expectBusUserId, //指定带看员
            expectPersonName: this.form.expectPersonName, //指定带看员姓名
            expectPersonTenantId: this.form.expectPersonTenantId, //指定带看员所属租户id
          }
          if (!form.workOrderId) {
            addWorkOrder(form).then(res => {
              if (res.code === 200) {
                uni.$u.toast('提交成功')
                setTimeout(() => {
                  this.$tab.redirectTo('./success?workOrderId=' + res.msg)
                }, 1000)
              } else {
                uni.$u.toast('提交失败')
              }
            })
          } else {
            editWorkOrder(form).then(res => {
              if (res.code === 200) {
                uni.$u.toast(res.msg || '修改成功')
                setTimeout(() => {
                  this.cancel()
                }, 1000)
              } else {
                uni.$u.toast('修改失败')
              }
            })
          }

        }
      }).catch(errors => {
        console.log('errors', errors)
        uni.$u.toast(errors[0].message||'请检查输入内容')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.container {
  background-color: #fff;
  padding: 20rpx;

  .form {
    padding: 20rpx;
    margin-bottom: 160rpx;

    .tips {
      margin: 20rpx 0;
      text-align: center;
      color: #999;
      font-size: 20rpx;
    }
  }

  .container-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 999;
    padding: 30rpx 20rpx;
    display: flex;
    justify-content: space-between;

    .btn {
      width: 100%;
      border-radius: 10rpx;
      border: 1rpx solid #ccc;

      &:last-child {
        margin-left: 20rpx;
      }
    }
  }

}

</style>